﻿using Castle.DynamicProxy;
using Newtonsoft.Json;
using System;
using System.Diagnostics;

namespace EyFramework.Common
{
    public class CallLogger : IInterceptor
    {
        public static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 动态代理拦截Service函数调用，记录调用日志,并记录花费时间
        /// </summary>
        /// <param name="invocation"></param>
        public void Intercept(IInvocation invocation)
        {
            Stopwatch sw = null;
            if (logger.IsDebugEnabled)
            {
                sw = new Stopwatch();
                sw.Start();
                logger.Debug("调用{0}.{1},入参:{2}", invocation.TargetType.FullName, invocation.Method.Name, JsonConvert.SerializeObject(invocation.Arguments));
            }
            else if (logger.IsInfoEnabled)
            {
                sw = new Stopwatch();
                sw.Start();
                logger.Info("调用{0}.{1}", invocation.TargetType.FullName, invocation.Method.Name);
            }

            try
            {
                invocation.Proceed();
            }
            catch (Exception ex)
            {
                logger.Error(ex, String.Format("调用{0}.{1}失败", invocation.TargetType.FullName, invocation.Method.Name));
                throw new Exception(ex.Message, ex);
            }
            //在被拦截的方法执行完毕后 继续执行
            if (logger.IsDebugEnabled)
            {
                sw.Stop();
                logger.Debug("函数{0}执行完毕，时间:{1}ms", invocation.Method.Name, sw.ElapsedMilliseconds);
            }
            else if (logger.IsInfoEnabled)
            {
                logger.Info("函数{0}执行完毕，时间:{1}ms", invocation.Method.Name, sw.ElapsedMilliseconds);
            }
        }
    }
}